# socket tcp server端demo
# 引入socket模块
import socket
# 创建socket实例
server = socket.socket()
print(server)
help(server.bind)

# 绑定本地地址
server.bind(('127.0.0.1', 9999))
print(server)
# 监听端口
server.listen()

help(server.accept) # accept 返回一个元组，(socket, remoteAddr)

s, ip = server.accept() # 接收客户端连接，返回socket和远程客户端地址
print('client ->', ip, s)

try:
    while True:
        data = s.recv(1024) # 接收缓冲区大小
        if data.decode('utf-8') == 'exit':
            print('client send exit')
            break
        print('recv data ->', data.decode('utf-8'))
        s.send('ack'.encode('utf-8'))
except Exception as e:
    print('socket error ->', e)
    raise e
finally:
    s.close()
    server.close()

